// admin.js - 管理员专属功能

window.renderUserManagement = function() {
  console.log('admin.js: renderUserManagement 被调用');
  let users = window.mockUsers || [];
  let contentArea = document.getElementById('contentArea');
  let html = `
    <div class="user-mgmt-header">
      <h4>用户管理</h4>
      <button class="btn btn-primary" id="addUserBtn">新增用户</button>
    </div>
    <div class="search-filter-container">
      <input type="text" id="searchInput" placeholder="搜索用户名、姓名、角色、部门..." class="form-control">
      <select id="roleFilter" class="form-control">
        <option value="">所有角色</option>
        <option value="admin">系统管理员</option>
        <option value="manager">物资管理员</option>
        <option value="doctor">医护人员</option>
      </select>
      <select id="statusFilter" class="form-control">
        <option value="">所有状态</option>
        <option value="启用">启用</option>
        <option value="禁用">禁用</option>
      </select>
    </div>
    <table class="table table-bordered user-table">
      <thead>
        <tr>
          <th>用户名</th>
          <th>姓名</th>
          <th>角色</th>
          <th>部门</th>
          <th>邮箱</th>
          <th>状态</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="userTableBody">
        ${users.map((u, idx) => `
          <tr data-idx="${idx}">
            <td>${u.username}</td>
            <td>${u.name}</td>
            <td>${roleName(u.role)}</td>
            <td>${u.department || ''}</td>
            <td>${u.email || ''}</td>
            <td>
              <span class="user-status ${u.status === '禁用' ? 'text-danger' : 'text-success'}">${u.status || '启用'}</span>
            </td>
            <td>
              <button class="btn btn-sm btn-info edit-user-btn">编辑</button>
              <button class="btn btn-sm btn-warning reset-pwd-btn">重置密码</button>
              <button class="btn btn-sm btn-secondary toggle-status-btn">${u.status === '禁用' ? '启用' : '禁用'}</button>
              <button class="btn btn-sm btn-danger delete-user-btn">删除</button>
            </td>
          </tr>
        `).join('')}
      </tbody>
    </table>
    <div id="userModal" class="modal" style="display:none;"></div>
    <div id="modalMask" class="modal-mask" style="display:none;"></div>
  `;
  contentArea.innerHTML = html;

  // 事件绑定
  document.getElementById('addUserBtn').onclick = () => showUserModal('add');
  document.querySelectorAll('.edit-user-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      showUserModal('edit', idx);
    }
  });
  document.querySelectorAll('.reset-pwd-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      showResetPwdModal(idx);
    }
  });
  document.querySelectorAll('.toggle-status-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      toggleUserStatus(idx);
    }
  });
  document.querySelectorAll('.delete-user-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      deleteUser(idx);
    }
  });

  // 搜索与筛选功能
  document.getElementById('searchInput').addEventListener('input', filterUsers);
  document.getElementById('roleFilter').addEventListener('change', filterUsers);
  document.getElementById('statusFilter').addEventListener('change', filterUsers);
}

function roleName(role) {
  return role === 'admin' ? '系统管理员' :
         role === 'manager' ? '物资管理员' :
         role === 'doctor' ? '医护人员' : role;
}

function showUserModal(type, idx) {
  let users = window.mockUsers || [];
  let user = type === 'edit' ? users[idx] : {};
  let modal = document.getElementById('userModal');
  let mask = document.getElementById('modalMask');
  modal.innerHTML = `
    <div class="modal-content">
      <h5>${type === 'add' ? '新增用户' : '编辑用户'}</h5>
      <form id="userForm">
        <label>用户名</label>
        <input type="text" name="username" value="${user.username || ''}" ${type === 'edit' ? 'readonly' : ''} required>
        <label>姓名</label>
        <input type="text" name="name" value="${user.name || ''}" required>
        <label>角色</label>
        <select name="role" required>
          <option value="admin" ${user.role === 'admin' ? 'selected' : ''}>系统管理员</option>
          <option value="manager" ${user.role === 'manager' ? 'selected' : ''}>物资管理员</option>
          <option value="doctor" ${user.role === 'doctor' ? 'selected' : ''}>医护人员</option>
        </select>
        <label>部门</label>
        <input type="text" name="department" value="${user.department || ''}">
        <label>邮箱</label>
        <input type="email" name="email" value="${user.email || ''}">
        <div class="modal-actions">
          <button type="submit" class="btn btn-primary">${type === 'add' ? '新增' : '保存'}</button>
          <button type="button" class="btn btn-secondary" id="closeUserModal">取消</button>
        </div>
      </form>
    </div>
  `;
  modal.style.display = 'block';
  mask.style.display = 'block';

  document.getElementById('closeUserModal').onclick = closeModal;
  mask.onclick = closeModal;

  document.getElementById('userForm').onsubmit = function(e) {
    e.preventDefault();
    const form = e.target;
    const newUser = {
      username: form.username.value.trim(),
      name: form.name.value.trim(),
      role: form.role.value,
      department: form.department.value.trim(),
      email: form.email.value.trim(),
      status: '启用'
    };
    if (type === 'add') {
      (window.mockUsers = window.mockUsers || []).push(newUser);
    } else {
      Object.assign(window.mockUsers[idx], newUser);
    }
    closeModal();
    window.renderUserManagement();
  }
}

function showResetPwdModal(idx) {
  let users = window.mockUsers || [];
  let user = users[idx];
  let modal = document.getElementById('userModal');
  let mask = document.getElementById('modalMask');
  modal.innerHTML = `
    <div class="modal-content">
      <h5>重置密码</h5>
      <form id="resetPwdForm">
        <label>新密码</label>
        <input type="password" name="password" required>
        <div class="modal-actions">
          <button type="submit" class="btn btn-primary">重置</button>
          <button type="button" class="btn btn-secondary" id="closeUserModal">取消</button>
        </div>
      </form>
    </div>
  `;
  modal.style.display = 'block';
  mask.style.display = 'block';

  document.getElementById('closeUserModal').onclick = closeModal;
  mask.onclick = closeModal;

  document.getElementById('resetPwdForm').onsubmit = function(e) {
    e.preventDefault();
    user.password = e.target.password.value;
    closeModal();
    window.renderUserManagement();
    alert('密码已重置');
  }
}

function toggleUserStatus(idx) {
  let users = window.mockUsers || [];
  let user = users[idx];
  user.status = user.status === '禁用' ? '启用' : '禁用';
  window.renderUserManagement();
}

function deleteUser(idx) {
  if (!confirm('确定要删除该用户吗？')) return;
  let users = window.mockUsers || [];
  users.splice(idx, 1);
  window.renderUserManagement();
}

function closeModal() {
  document.getElementById('userModal').style.display = 'none';
  document.getElementById('modalMask').style.display = 'none';
}

function filterUsers() {
  const searchInput = document.getElementById('searchInput').value.toLowerCase();
  const roleFilter = document.getElementById('roleFilter').value;
  const statusFilter = document.getElementById('statusFilter').value;
  const users = window.mockUsers || [];
  const filteredUsers = users.filter(user => {
    const matchesSearch = user.username.toLowerCase().includes(searchInput) ||
                         user.name.toLowerCase().includes(searchInput) ||
                         roleName(user.role).toLowerCase().includes(searchInput) ||
                         (user.department || '').toLowerCase().includes(searchInput);
    const matchesRole = !roleFilter || user.role === roleFilter;
    const matchesStatus = !statusFilter || user.status === statusFilter;
    return matchesSearch && matchesRole && matchesStatus;
  });
  renderFilteredUsers(filteredUsers);
}

function renderFilteredUsers(users) {
  const tbody = document.getElementById('userTableBody');
  tbody.innerHTML = users.map((u, idx) => `
    <tr data-idx="${idx}">
      <td>${u.username}</td>
      <td>${u.name}</td>
      <td>${roleName(u.role)}</td>
      <td>${u.department || ''}</td>
      <td>${u.email || ''}</td>
      <td>
        <span class="user-status ${u.status === '禁用' ? 'text-danger' : 'text-success'}">${u.status || '启用'}</span>
      </td>
      <td>
        <button class="btn btn-sm btn-info edit-user-btn">编辑</button>
        <button class="btn btn-sm btn-warning reset-pwd-btn">重置密码</button>
        <button class="btn btn-sm btn-secondary toggle-status-btn">${u.status === '禁用' ? '启用' : '禁用'}</button>
        <button class="btn btn-sm btn-danger delete-user-btn">删除</button>
      </td>
    </tr>
  `).join('');
  // 重新绑定事件
  document.querySelectorAll('.edit-user-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      showUserModal('edit', idx);
    }
  });
  document.querySelectorAll('.reset-pwd-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      showResetPwdModal(idx);
    }
  });
  document.querySelectorAll('.toggle-status-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      toggleUserStatus(idx);
    }
  });
  document.querySelectorAll('.delete-user-btn').forEach(btn => {
    btn.onclick = function() {
      const idx = this.closest('tr').dataset.idx;
      deleteUser(idx);
    }
  });
}

// 模拟权限数据（默认医护人员所有菜单都启用）
window.mockPermissions = window.mockPermissions || {
    doctor: {
        '急救车物资概览': true,
        '物资出库/使用登记': true,
        '物资申领/补充申请': true,
        '物资异常报告': true,
        '物资使用历史': true,
        '物资有效期预警': true,
        '物资库存预警': true,
        '物资资料查询': true
    },
    manager: {
        '急救车物资配置': true,
        '物资信息管理': true,
        '物资库存管理': true,
        '急救车补充管理': true,
        '盘点记录': true
    }
};

window.renderPermissionManagement = function() {
    console.log('admin.js: renderPermissionManagement 被调用');
    const contentArea = document.getElementById('contentArea');
    if (!contentArea) return;

    const doctorMenus = window.mockMenus.doctor || [];
    const currentDoctorPermissions = window.mockPermissions.doctor || {};

    const managerMenus = window.mockMenus.manager || [];
    const currentManagerPermissions = window.mockPermissions.manager || {};

    let html = `
        <div class="permission-mgmt-header">
            <h4>权限管理</h4>
        </div>
        <div class="card mb-4">
            <div class="card-header">医护人员模块权限</div>
            <div class="card-body">
                <table class="table table-bordered permission-table">
                    <thead>
                        <tr>
                            <th>模块名称</th>
                            <th>描述</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="doctorPermissionTableBody">
                        ${doctorMenus.map(menu => {
                            const isEnabled = currentDoctorPermissions[menu.title] !== false; // 默认启用
                            return `
                                <tr>
                                    <td>${menu.title}</td>
                                    <td>${menu.desc}</td>
                                    <td><span class="badge ${isEnabled ? 'bg-success' : 'bg-danger'}">${isEnabled ? '已启用' : '已禁用'}</span></td>
                                    <td>
                                        <button class="btn btn-sm ${isEnabled ? 'btn-warning' : 'btn-success'} toggle-permission-btn" data-role="doctor" data-module="${menu.title}">${isEnabled ? '禁用' : '启用'}</button>
                                    </td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>
            </div>
        </div>

        <div class="card">
            <div class="card-header">物资管理人员模块权限</div>
            <div class="card-body">
                <table class="table table-bordered permission-table">
                    <thead>
                        <tr>
                            <th>模块名称</th>
                            <th>描述</th>
                            <th>状态</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="managerPermissionTableBody">
                        ${managerMenus.map(menu => {
                            const isEnabled = currentManagerPermissions[menu.title] !== false; // 默认启用
                            return `
                                <tr>
                                    <td>${menu.title}</td>
                                    <td>${menu.desc}</td>
                                    <td><span class="badge ${isEnabled ? 'bg-success' : 'bg-danger'}">${isEnabled ? '已启用' : '已禁用'}</span></td>
                                    <td>
                                        <button class="btn btn-sm ${isEnabled ? 'btn-warning' : 'btn-success'} toggle-permission-btn" data-role="manager" data-module="${menu.title}">${isEnabled ? '禁用' : '启用'}</button>
                                    </td>
                                </tr>
                            `;
                        }).join('')}
                    </tbody>
                </table>
                <div class="modal-actions">
                    <button class="btn btn-primary" id="savePermissionsBtn">保存更改</button>
                    <button class="btn btn-secondary" id="cancelPermissionsBtn">取消</button>
                </div>
            </div>
        </div>
    `;
    contentArea.innerHTML = html;

    // 事件绑定
    document.querySelectorAll('.toggle-permission-btn').forEach(btn => {
        btn.onclick = function() {
            const role = this.dataset.role;
            const moduleName = this.dataset.module;
            if (role === 'doctor') {
                toggleDoctorModulePermission(moduleName);
            } else if (role === 'manager') {
                toggleManagerModulePermission(moduleName);
            }
        };
    });

    document.getElementById('savePermissionsBtn').onclick = savePermissions;
    document.getElementById('cancelPermissionsBtn').onclick = cancelPermissions;
};

// 切换医护人员模块权限
function toggleDoctorModulePermission(moduleName) {
    window.mockPermissions.doctor[moduleName] = !window.mockPermissions.doctor[moduleName];
    window.renderPermissionManagement(); // 重新渲染以反映更改
}

// 切换物资管理人员模块权限
function toggleManagerModulePermission(moduleName) {
    window.mockPermissions.manager[moduleName] = !window.mockPermissions.manager[moduleName];
    window.renderPermissionManagement(); // 重新渲染以反映更改
}

// 保存权限更改
function savePermissions() {
    alert('权限更改已保存！');
    // 实际应用中，这里会发送请求到后端保存权限
}

// 取消权限更改
function cancelPermissions() {
    // 重新加载权限管理界面，放弃当前未保存的更改
    window.renderPermissionManagement();
}

window.renderSystemConfig = function() {
  console.log('admin.js: renderSystemConfig 被调用');
  let contentArea = document.getElementById('contentArea');
  let html = `
    <div class="system-config-header">
      <h4>系统配置</h4>
    </div>
    <div class="system-config-container">
      <h5>系统参数设置</h5>
      <form id="systemConfigForm">
        <div class="form-group">
          <label>系统名称</label>
          <input type="text" name="systemName" value="医院病区急救车物资综合管理系统" class="form-control">
        </div>
        <div class="form-group">
          <label>日志保留天数</label>
          <input type="number" name="logRetentionDays" value="30" class="form-control">
        </div>
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">保存配置</button>
          <button type="button" class="btn btn-secondary" id="resetConfig">重置</button>
        </div>
      </form>
    </div>
    <div class="system-logs-container">
      <h5>系统日志</h5>
      <table class="table table-bordered">
        <thead>
          <tr>
            <th>时间</th>
            <th>级别</th>
            <th>操作</th>
            <th>用户</th>
            <th>详情</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>2025-01-01 10:00:05</td>
            <td>INFO</td>
            <td>系统启动</td>
            <td>系统</td>
            <td>后台服务初始化完成</td>
          </tr>
          <tr>
            <td>2025-01-02 10:05:30</td>
            <td>INFO</td>
            <td>用户登录</td>
            <td>admin</td>
            <td>管理员成功登录系统</td>
          </tr>
          <tr>
            <td>2025-01-03 10:10:15</td>
            <td>INFO</td>
            <td>用户登录</td>
            <td>manager</td>
            <td>物资管理人员登录成功</td>
          </tr>
          <tr>
            <td>2025-01-04 10:15:40</td>
            <td>INFO</td>
            <td>用户登录</td>
            <td>doctor</td>
            <td>医护人员登录成功</td>
          </tr>
          <tr>
            <td>2025-01-05 10:20:00</td>
            <td>WARNING</td>
            <td>系统配置更新</td>
            <td>admin</td>
            <td>更新了日志保留天数</td>
          </tr>
          <tr>
            <td>2025-01-06 11:30:20</td>
            <td>INFO</td>
            <td>物资入库</td>
            <td>manager</td>
            <td>入库急救包 x 5</td>
          </tr>
          <tr>
            <td>2025-01-07 14:00:10</td>
            <td>ERROR</td>
            <td>数据同步失败</td>
            <td>系统</td>
            <td>与外部数据源连接中断</td>
          </tr>
          <tr>
            <td>2025-01-08 16:45:55</td>
            <td>INFO</td>
            <td>用户管理</td>
            <td>admin</td>
            <td>新增用户: 徐医生</td>
          </tr>
        </tbody>
      </table>
    </div>
  `;
  contentArea.innerHTML = html;

  // 事件绑定
  document.getElementById('systemConfigForm').onsubmit = function(e) {
    e.preventDefault();
    showToast('系统配置已保存');
  };
  document.getElementById('resetConfig').onclick = function() {
    document.getElementById('systemConfigForm').reset();
    showToast('系统配置已重置');
  };
}

// 初始化系统概览
function initSystemOverview() {
  const overviewContainer = document.getElementById('system-overview');
  if (!overviewContainer) return;

  // 模拟系统状态数据
  const systemStatus = {
    status: '正常运行',
    onlineUsers: 5,
    pendingTasks: 2
  };

  // 更新系统概览内容为卡片样式
  overviewContainer.innerHTML = `
    <div class="overview-item">
      <h3>系统状态</h3>
      <p>${systemStatus.status}</p>
    </div>
    <div class="overview-item">
      <h3>在线用户</h3>
      <p>${systemStatus.onlineUsers}</p>
    </div>
    <div class="overview-item">
      <h3>待处理事项</h3>
      <p>${systemStatus.pendingTasks}</p>
    </div>
  `;
}

// 初始化近期系统日志
function initRecentLogs() {
  const logsContainer = document.getElementById('recent-logs');
  if (!logsContainer) return;

  // 模拟近期系统日志数据
  const recentLogs = [
    { time: '2025-01-08 16:45:55', level: 'INFO', operation: '用户管理', user: 'admin', details: '新增用户: 李医生' },
    { time: '2025-01-07 14:00:10', level: 'ERROR', operation: '数据同步失败', user: '系统', details: '与外部数据源连接中断' },
    { time: '2025-01-06 11:30:20', level: 'INFO', operation: '物资入库', user: 'manager', details: '入库急救包 x 5' },
    { time: '2025-01-05 10:20:00', level: 'WARNING', operation: '系统配置更新', user: 'admin', details: '更新了日志保留天数' }
  ];

  // 更新近期系统日志内容为表格样式
  logsContainer.innerHTML = `
    <table>
      <thead>
        <tr>
          <th>时间</th>
          <th>级别</th>
          <th>操作</th>
          <th>用户</th>
          <th>详情</th>
        </tr>
      </thead>
      <tbody>
        ${recentLogs.map(log => `
          <tr>
            <td>${log.time}</td>
            <td>${log.level}</td>
            <td>${log.operation}</td>
            <td>${log.user}</td>
            <td>${log.details}</td>
          </tr>
        `).join('')}
      </tbody>
    </table>
  `;
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
  initSystemOverview();
  initRecentLogs();
});

window.renderDashboard = function() {
  const contentArea = document.getElementById('contentArea');
  contentArea.innerHTML = `
    <div class="welcome-container">
      <h1 class="welcome-title">
        <i class="fas fa-hospital me-2"></i>
        欢迎使用医院病区急救车物资管理系统
      </h1>
    </div>`;
  initSystemOverview();
  initRecentLogs();
};

// 刷新仪表盘数据
function refreshDashboard() {
  showToast('数据已刷新');
  window.renderDashboard();
}

// 查看所有日志
function viewAllLogs() {
  window.renderSystemConfig();
}

